package tgc.edu.demo.jkxt.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashSet;
import java.util.List;
import java.util.UUID;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.Base64Utils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import tgc.edu.demo.jkxt.custom.AjaxResult;
import tgc.edu.demo.jkxt.custom.BaseController;
import tgc.edu.demo.jkxt.custom.TablePageable;
//import tgc.edu.demo.jkxt.entity.Grade;
import tgc.edu.demo.jkxt.entity.Student;
import tgc.edu.demo.jkxt.entity.SysRole;
import tgc.edu.demo.jkxt.form.StudentForm;
//import tgc.edu.demo.jkxt.service.GradeService;
import tgc.edu.demo.jkxt.service.StudentService;
import tgc.edu.demo.jkxt.service.TbClassService;

@RestController
@RequestMapping(value = "/student")
@CrossOrigin
public class StudentController extends BaseController <Student,Integer,StudentForm>{
	@Value("${web.file-path}")
	private String path;
	@Autowired
	private StudentService service;
	@Autowired
	private TbClassService bjService;
//	@Autowired
//	private GradeService gradeService;

	
	
	@SuppressWarnings("serial")
	public Specification<Student> buildSpec(StudentForm form){
		Specification<Student> spec =new Specification<Student>() {
			
			@Override
			public Predicate toPredicate(Root<Student> root,CriteriaQuery<?> query,CriteriaBuilder criteriaBuilder) {
				HashSet<Predicate> rules = new HashSet<>();
				Integer tbClassId = form.getTbClassId();
				
				if(tbClassId!=null) {
					rules.add(criteriaBuilder.equal(root.get("tbClass").get("id"), tbClassId));
				}
				String search = form.getSearch();
				if(StringUtils.hasText(search)) {
					HashSet<Predicate> rules2=new HashSet<>();
					rules2.add(criteriaBuilder.like(root.get("stuNo"),"%"+search+"%"));
					rules2.add(criteriaBuilder.like(root.get("name"),"%"+search+"%"));
					rules2.add(criteriaBuilder.like(root.get("sex"),"%"+search+"%"));
								
					rules.add(criteriaBuilder.or(rules2.toArray(new Predicate[rules2.size()])));
				}
				return criteriaBuilder.and(rules.toArray(new Predicate[rules.size()]));
				
			}
		};
		return spec;
	}
	@RequestMapping(value = "/czmm")
	@ResponseBody
	public Object resetPwd(StudentForm form) {
		Integer id = form.getId();
		Student model=service.findById(id);
		//重置密码
		model.setPassword(new BCryptPasswordEncoder().encode("1111"));
		service.save(model);
		return true;
	}
	@RequestMapping(value = "/bytb")
	@ResponseBody
	public Object findByTbClassId(Integer bjid) {

		List<Student> list=service.findByTbClassId(bjid);
		return new AjaxResult(list); 
	}
	
	@RequestMapping(value = "/byid")
	@ResponseBody
	public Object findById(Integer id) {
		
		Student student=service.findById(id);
		return new AjaxResult(student); 
	}
	
	@Override
	public Object save(StudentForm form) {
		try {
			Student model=new Student();
			Integer id = form.getId();
			if(id!=null) {
				model=service.findById(id);
			}else {
				model.setPassword(new BCryptPasswordEncoder().encode("1111"));
				model.setTbClass(bjService.findById(form.getTbClassId()));
				model.getRoles().add(new SysRole(3));
			}
			
//			MultipartFile file = form.getFile();
//			if(file!=null) {
//				String filename = file.getOriginalFilename();
//				if(StringUtils.hasText(filename)) {
//					String uuid = model.getUuid();
//					if(uuid!=null) {
//						new File(path,uuid).delete();
//					}
//					model.setFilename(filename);
//					uuid=UUID.randomUUID().toString();
//					model.setUuid(uuid);
//					file.transferTo(new File(path,uuid));
//				}
//			}
			BeanUtils.copyProperties(form, model,"id");
			model.setUsername(model.getStuNo());
			
			service.save(model);
			return new AjaxResult("数据保存成功");
		} catch (Exception e) {
			e.printStackTrace();
			//return new AjaxResult(false, "数据保存失败");
		}
		return null;
}
	
	
	
	private String getStr(HttpServletRequest request, String fileName) {
		String downloadFileName = null;		
		String agent = request.getHeader("USER-AGENT");
		try {
			if (agent != null && agent.toLowerCase().indexOf("firefox") > 0) {
				
				downloadFileName = "=?UTF-8?B?" + Base64Utils.encodeToString(fileName.getBytes("UTF-8")) + "?=";
			} else {
				downloadFileName = java.net.URLEncoder.encode(fileName, "UTF-8");
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return downloadFileName;
	}
}
